import Ionicons from '@expo/vector-icons/Ionicons';
import { StyleSheet, Image, Platform, View, TouchableOpacity, Modal, Pressable, Alert, useWindowDimensions, KeyboardAvoidingView } from 'react-native';

import { Collapsible } from '@/components/Collapsible';
import { ExternalLink } from '@/components/ExternalLink';
import ParallaxScrollView from '@/components/ParallaxScrollView';
import { ThemedText } from '@/components/ThemedText';
import { ThemedView } from '@/components/ThemedView';
import { atom, useAtom, useAtomValue } from 'jotai';
import { atomWithStorage, createJSONStorage, loadable, unwrap } from "jotai/utils";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { Appbar, Banner, Button, IconButton, RadioButton, SegmentedButtons, Text, TextInput, Title } from 'react-native-paper';
import QRCode from 'react-native-qrcode-svg';
import { SafeAreaView } from 'react-native-safe-area-context';
import RNPermissions from "react-native-permissions";
import Toast from 'react-native-simple-toast';
import { Suspense, useEffect, useRef, useState } from 'react';
import BottomSheet, { BottomSheetModal, BottomSheetModalProvider, BottomSheetView } from '@gorhom/bottom-sheet';
import { CameraView, CameraType, useCameraPermissions } from 'expo-camera';
import { Link, Tabs, useLocalSearchParams, useRouter } from 'expo-router';
import { TabBarIcon } from '@/components/navigation/TabBarIcon';
import Qrscan from '../qrscan';
import { PickFunVersion, qrCodeSettingAtom, PickFunDeviceModel, scannedDevSpecAtom } from '../../store';
import * as FileSystem from 'expo-file-system'
import { captureRef } from 'react-native-view-shot';
import { SystemBars } from 'react-native-edge-to-edge';
import { getDevSpecDescription } from '@/utils';
import * as Clipboard from 'expo-clipboard';




//设备的版本，海外/国内
const versionOfPickfunAtom = atom(
  async (get) => {
    const settings = await get(qrCodeSettingAtom);
    return settings.version;
  },
  async (_get, set, value: string) => {
    set(qrCodeSettingAtom, async (v) => {
      const org = await v;
      return { ...org, version: value as PickFunVersion };
    })
  }
);

const modelAtom = atom<PickFunDeviceModel>(PickFunDeviceModel.p0);

//设备序列号
const snAtom = atom(
  async (get) => {
    const settings = await get(qrCodeSettingAtom);
    return settings.sn;
  },
  async (_get, set, value: string) => {
    set(qrCodeSettingAtom, async (v) => {
      const org = await v;
      return { ...org, sn: value };
    })
  });

const qrcodeAtom = atom(
  async (get) => {
    const sn = await get(snAtom);
    if (!sn) {
      return "";
    }
    const model = get(modelAtom);
    const devVersion = await get(versionOfPickfunAtom);
    switch (model) {
      case PickFunDeviceModel.p0:
        switch (devVersion) {
          case PickFunVersion.china:
            return `https://h5.pick-fun.com.cn/download.html?mac=&m=0&s=${sn}`
          case PickFunVersion.oversea:
            return `https://h5.pick-fun.com/download.html?mac=&m=0&s=${sn}`
        }
      case PickFunDeviceModel.p1:
        switch (devVersion) {
          case PickFunVersion.china:
            return `https://h5.pick-fun.com.cn/download.html?mac=&sn=${sn}`
          case PickFunVersion.oversea:
            return `https://www.pick-fun.com/qrcode/device/bottom?mac=&sn=${sn}`
        }
      case PickFunDeviceModel.p3:
        switch (devVersion) {
          case PickFunVersion.china:
            return `https://h5.pick-fun.com.cn/download.html?mac=&m=3&s=${sn}`
          case PickFunVersion.oversea:
            return `https://h5.pick-fun.com/download.html?mac=&m=3&s=${sn}`
        }
      case PickFunDeviceModel.a3:
        switch (devVersion) {
          case PickFunVersion.china:
            return `https://h5.pick-fun.com.cn/download.html?mac=&m=a3&s=${sn}`
          case PickFunVersion.oversea:
            return `https://h5.pick-fun.com/download.html?mac=&m=a3&s=${sn}`
        }
    }
  })

const unwrappedQrcodeAtom = unwrap(qrcodeAtom, (prev) => prev ?? "")
const unwrappedSnAtom = unwrap(snAtom, (prev) => prev ?? "")
const unwrappedPickfunVersionAtom = unwrap(versionOfPickfunAtom, (prev) => prev ?? PickFunVersion.oversea)

export default function TabTwoScreen() {
  const [sn, setSn] = useAtom(unwrappedSnAtom);
  const qr = useAtomValue(unwrappedQrcodeAtom);
  const inputRef = useRef<any>(null)
  const router = useRouter();
  const [bannerVisible, setBannerVisible] = useState(false);
  const [scannedDevSpec, setScannedDevSpec] = useAtom(scannedDevSpecAtom);
  const [qrScanStartedBy, setQrScanStartedBy] = useState<null | "textInput">(null);
  const [scannerVisible, setScannerVisible] = useState(false);
  const [versionOfPickfun, setVersionOfPickfun] = useAtom(unwrappedPickfunVersionAtom);
  const qrRef = useRef<any>(null);
  const [model, setModel] = useAtom(modelAtom);


  async function loadData() {
    const resp = await fetch("https://fakestoreapi.com/products/1")
    const json = await resp.json()
    console.log(JSON.stringify(json, null, 2))
  }

  useEffect(() => {
    if (qrScanStartedBy === 'textInput' && scannedDevSpec) {
      setSn(scannedDevSpec!.sn!);
    }
    setBannerVisible(!!scannedDevSpec && !qrScanStartedBy);
  }, [scannedDevSpec, qrScanStartedBy]);


  return (
    <>
      <SystemBars style="auto" />
      <Tabs.Screen
        options={{
          title: '主页',
          headerShown: true,
          headerTitle: () =>
            <Pressable
              onPress={() => {
                Alert.alert("title", "message",)
              }}
            >
              <Text variant='titleLarge'>皮克方二维码生成器</Text>
            </Pressable>,
          headerRight: () => (
            <Link href="/qrscan" asChild>
              <IconButton
                icon={"line-scan"}
                onPress={() => {
                  setScannedDevSpec(null)
                  setQrScanStartedBy(null)
                  //router.push("/qrscan")
                  //setScannerVisible(true)
                }} />
            </Link>),
          tabBarIcon: ({ color, focused }) => (
            <TabBarIcon name={focused ? 'home' : 'home-outline'} color={color} />
          ),
        }}
      />
      <KeyboardAvoidingView
        behavior='padding'
        keyboardVerticalOffset={100}
        className='flex-1'>
        <Banner
          visible={bannerVisible}
          style={{ zIndex: 1000 }}
          actions={
            [
              {
                label: '确定',
                onPress: () => {
                  //scannedSn = ""
                  setBannerVisible(false)
                },
              },
              {
                label: '提取SN',
                onPress: async () => {
                  //scannedSn = ""
                  var sn = scannedDevSpec?.sn;
                  if (sn) {
                    setSn(sn);
                    await Clipboard.setStringAsync(sn);
                    Toast.showWithGravity("SN已经复制到剪贴板", Toast.SHORT, Toast.CENTER);
                  } else {
                    Toast.showWithGravity("无法提取SN, 请手动输入SN", Toast.SHORT, Toast.CENTER);
                  }
                  setBannerVisible(false);
                },
              },
            ]
          }
        >
          <Text
            variant='titleMedium'
            className='mb-2'
          >
            {`${getDevSpecDescription(scannedDevSpec)}`}
          </Text>
        </Banner>

        <View className='items-center justify-center flex-1'>
          {
            qr ?
              <View className='items-center'>
                <View >
                  <QRCode size={200} value={qr.trim()} quietZone={16} getRef={c => qrRef.current = c} />
                </View>
              </View>
              : <Text
                variant='titleLarge'
                className='m-8'
              >
                输入序列号，或者点击右上角图标, 可以扫描设备二维码, 识别机器版本和提取SN
              </Text>
          }
        </View>
        <View className='flex flex-col justify-around m-4' >
          <Text variant='titleSmall' className='mb-1'>型号</Text>
          <SegmentedButtons
            value={model}
            onValueChange={newValue => setModel(newValue as PickFunDeviceModel)}
            buttons={[
              {
                value: PickFunDeviceModel.p0,
                label: 'P0',
              },
              {
                value: PickFunDeviceModel.p1,
                label: 'P1',
              },
              {
                value: PickFunDeviceModel.p3,
                label: '猫砂盆'
              },
              {
                value: PickFunDeviceModel.a3,
                label: 'A3'
              },
            ]}
          />
          <Text variant='titleSmall' className='mt-6 mb-1'>版本</Text>
          <SegmentedButtons
            value={versionOfPickfun}
            onValueChange={newValue => setVersionOfPickfun(newValue as PickFunVersion)}
            buttons={[
              {
                value: PickFunVersion.oversea,
                label: '国际版',
              },
              {
                value: PickFunVersion.china,
                label: '国内版',
              },
            ]}
          />
        </View>
        <TextInput
          ref={inputRef}
          className='m-4 mt-8 mb-8'
          mode="outlined"
          label='设备SN'
          placeholder='请输入设备SN'
          value={sn}
          right={sn &&
            <TextInput.Icon
              icon="close"
              onPress={() => {
                setSn("");
              }}
            />}
          onChangeText={setSn} />
      </KeyboardAvoidingView>
    </>
  );
}

const styles = StyleSheet.create({
  headerImage: {
    color: '#808080',
    bottom: -90,
    left: -35,
    position: 'absolute',
  },
  titleContainer: {
    flexDirection: 'row',
    gap: 8,
  },
});
